package com.ruoyi.lightkillPest.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.lightkillPest.domain.device.LightKillPestDeviceInfo;
import com.ruoyi.lightkillPest.mapper.LightKillPestDeviceMapper;
import com.ruoyi.lightkillPest.service.LightKillPestDeviceForGuangXunService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class LightKillPestDeviceForGuangXunServiceImpl implements LightKillPestDeviceForGuangXunService {

    @Autowired
    private LightKillPestDeviceMapper deviceMapper;
    @Override
    public String getToken(Integer deviceId) {

        LightKillPestDeviceInfo deviceInfo = deviceMapper.selectDeviceById(deviceId);
        String userName = deviceInfo.getGuangxunUserId();
        String password = deviceInfo.getGuangxunUserPassword();
        String urlLogin="http://guangxun-wulian.com/prod-api/remote/token";
        String token="";
        //创建post请求对象
        HttpPost post = new HttpPost(urlLogin);
        try {
            //创建参数集合
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            //添加参数
            list.add(new BasicNameValuePair("username",userName));
            list.add(new BasicNameValuePair("password",password));
            list.add(new BasicNameValuePair("grant_type","password"));
            //把参数放入请求对象，，post发送的参数list，指定格式
            post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            //添加请求头参数
            post.addHeader("Authorization","Basic cmVtb3RlOmNjY2IyMWJlYWM3Y2FmZjNkY2E0MTkxMTg1NjQ0ODI1M2Y5OTQwZjdhNzI5ZjQxMThmMzdkOTUwMmVmNjRmNWY=");
            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute(post);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //把实体对象转换为string
            String result = EntityUtils.toString(entity, "UTF-8");
            //返回内容
            //System.out.println(result);
            //System.out.println("-------------");
            JSONObject jsonobject = JSONObject.parseObject(result );
            token = jsonobject.getString("access_token");
            //detectionLogList = JSON.parseArray(entity.getBody(), DetectionLog.class);
            //System.out.println(token);
            //释放链接
            response.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return token;
    }

    public String getDeviceInfo(String guangxunId,String token){

        String result = "";
        URIBuilder uriBuilder = null;
        try {
            String urlDetail="http://guangxun-wulian.com/prod-api/remote/device/detail";

            //创建get请求对象
            uriBuilder = new URIBuilder(urlDetail);//你的host
            uriBuilder.setParameter("devicecode",guangxunId);

            HttpGet get = new HttpGet(uriBuilder.build());


            //添加请求头参数
            get.addHeader("Authorization","Bearer "+token);
            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute(get);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //把实体对象转换为string
            result = EntityUtils.toString(entity, "UTF-8");

            //释放链接
            response.close();

        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return result;
    }



    public String getDeviceList(String token) {
        String result="";
        URIBuilder uriBuilder = null;

        try {
            String urlDetail="http://guangxun-wulian.com/prod-api/remote/device/list";
            //创建get请求对象
            uriBuilder = new URIBuilder(urlDetail);
            HttpGet get = new HttpGet(uriBuilder.build());

            //添加请求头参数
            get.addHeader("Authorization","Bearer "+token);
            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute(get);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //把实体对象转换为string
            result = EntityUtils.toString(entity, "UTF-8");

            //释放链接
            response.close();

        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return result;
    }

    @Override
    public void refreshfindDevice(String guangxunId,String token){
        String url="http://guangxun-wulian.com/prod-api/remote/operation/refreshfind";
        HttpPost post = new HttpPost(url);
        try {
            //装填参数

            JSONObject param = new JSONObject();
            ArrayList<String> devicecodes = new ArrayList<>();
            devicecodes.add(guangxunId);
            param.put("devicecodes", devicecodes);
            param.put("devicetype", "8");
            param.put("type", 2);
            param.put("typeinfo", "REALTIME");
            //String json="{devicecodes: [\""+id+"\"], devicetype: \"8\", type: 2, typeinfo: \"REALTIME\"}";
            StringEntity s = new StringEntity(param.toString(), "utf-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            //设置参数到请求对象中
            post.setEntity(s);
            //添加请求头参数
            post.addHeader("Authorization","Bearer "+token);
            post.setHeader("Content-type", "application/json");

            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute(post);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //把实体对象转换为string
            String result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result);
            System.out.println("更新成功");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public int changeDeviceOnOff(String deviceCode,String onOff,String light,String token,String transport) {
        String urlChange="http://guangxun-wulian.com/prod-api/remote/operation/change";
        HttpPost post = new HttpPost(urlChange);
        try {
            //装填json参数
            String json="{\"devicecodes\":[\""+ deviceCode +"\"],\"devicetype\":\"8\",\"qakey\":[\"onoff\",\"light\",\"transport\"],\"value\":["+onOff+","+light+","+transport+"],\"typeinfo\":\"COMMON\"}";
            StringEntity s = new StringEntity(json, "utf-8");

            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            //设置参数到请求对象中
            post.setEntity(s);
            //添加请求头参数
            post.addHeader("Authorization","Bearer "+token);
            post.setHeader("Content-type", "application/json");
            post.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute(post);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //释放链接
            response.close();

        } catch (Exception e1) {
            e1.printStackTrace();
            return 0;
        }
        return 1;
    }
    @Override
    /**
     * loadWorkMode 设备负载工作模式： 0：定时模式 1：光控模式  3：常开模式  4：常关模式  5：测试模式
     */
    public int changeLoadWorkMode(String guangxunId,String loadWorkMode,String token) {
        String urlChange = "http://guangxun-wulian.com/prod-api/remote/advanced/setdevadv";
        HttpPost httpPost  = new HttpPost(urlChange);
        try {
            //装填参数formData形式
            //所有参数不得为空
            List pair = new ArrayList();
            pair.add(new BasicNameValuePair("loadworkmode",loadWorkMode));
            pair.add(new BasicNameValuePair("devicecode",guangxunId));
            pair.add(new BasicNameValuePair("powerload","90"));
            pair.add(new BasicNameValuePair("ligntonduration","5"));
            pair.add(new BasicNameValuePair("timeturnon","852"));
            pair.add(new BasicNameValuePair("timeturnoff","870"));
            pair.add(new BasicNameValuePair("time1","300"));
            pair.add(new BasicNameValuePair("time2","0"));
            pair.add(new BasicNameValuePair("time3","0"));
            pair.add(new BasicNameValuePair("time4","0"));
            pair.add(new BasicNameValuePair("time5","0"));
            pair.add(new BasicNameValuePair("timedown","0"));
            pair.add(new BasicNameValuePair("powerpeople1","100"));
            pair.add(new BasicNameValuePair("powerpeople2","100"));
            pair.add(new BasicNameValuePair("powerpeople3","100"));
            pair.add(new BasicNameValuePair("powerpeople4","100"));
            pair.add(new BasicNameValuePair("powerpeople5","100"));
            pair.add(new BasicNameValuePair("powerdawnpeople","100"));
            pair.add(new BasicNameValuePair("inductionswitch","0"));
            pair.add(new BasicNameValuePair("powersensor1","0"));
            pair.add(new BasicNameValuePair("powersensor2","0"));
            pair.add(new BasicNameValuePair("powersensor3","0"));
            pair.add(new BasicNameValuePair("powersensor4","0"));
            pair.add(new BasicNameValuePair("powersensor5","0"));
            pair.add(new BasicNameValuePair("powersensordown","0"));
            pair.add(new BasicNameValuePair("inductionlightondelay","30"));
            pair.add(new BasicNameValuePair("lowpowerconsumption","0"));
            pair.add(new BasicNameValuePair("battype","3"));
            pair.add(new BasicNameValuePair("batstringnum","3"));
            pair.add(new BasicNameValuePair("savingswitch","0"));
            pair.add(new BasicNameValuePair("firdownpower","1100"));
            pair.add(new BasicNameValuePair("twodownpower","1050"));
            pair.add(new BasicNameValuePair("threedownpower","1000"));
            pair.add(new BasicNameValuePair("firreducamplitude","60"));
            pair.add(new BasicNameValuePair("tworeducamplitude","40"));
            pair.add(new BasicNameValuePair("threereducamplitude","20"));
            pair.add(new BasicNameValuePair("temcontrolswitch","0"));
            pair.add(new BasicNameValuePair("customeswitch","0"));
            pair.add(new BasicNameValuePair("volcharge","1080"));
            pair.add(new BasicNameValuePair("voloverdischarge","750"));
            pair.add(new BasicNameValuePair("icharge","800"));
            pair.add(new BasicNameValuePair("tempcharge","55395"));
            pair.add(new BasicNameValuePair("tempdischarge","55395"));
            pair.add(new BasicNameValuePair("switchdelaytime","65533"));
            pair.add(new BasicNameValuePair("autosleeptime","0"));
            pair.add(new BasicNameValuePair("vpv","500"));
            pair.add(new BasicNameValuePair("pvswitch","1"));
            pair.add(new BasicNameValuePair("inspectiontime","30"));
            pair.add(new BasicNameValuePair("devicetype","8"));

            httpPost.setEntity(new UrlEncodedFormEntity(pair));
            //添加请求头参数
            httpPost.addHeader("Authorization","Bearer "+token);
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute(httpPost);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //释放链接
            response.close();

        } catch (Exception e1) {
            e1.printStackTrace();
            return 0;
        }
        return 1;
    }



}
